
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin: 20px 0">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数!"
        type="warning"
        effect="dark"
        class="el-icon-warning"
        :closable="false"
      >
      </el-alert>
      <div style="margin: 20px">
        <span>选择商品分类：</span>
        <el-cascader
          v-model="selectedCateKeys"
          :options="cateList"
          expandTrigger="hover"
          :props="cateProps"
          @change="handleChange"
        ></el-cascader>
        <el-tabs
          v-model="activeName"
          type="card"
          style="margin-top: 20px"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="用户管理" name="many">
            <el-button
              type="primary"
              size="mini"
              :disabled="isButtonDisabled"
              @click="dialogVisible = true"
            >
              添加参数</el-button
            >

            <el-table :data="manyTableData" style="width: 100%" border>
              <el-table-column type="expand">
                <template v-slot="scope">
                  <el-tag
                    closable
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    @close="handleClose(index, scope.row)"
                  >
                    {{ item }}
                  </el-tag>
                  <el-input
                    style="width: 100px"
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="#" type="index"> </el-table-column>
              <el-table-column label="参数名称" prop="attr_name">
              </el-table-column>
              <el-table-column label="操作">
                <template v-slot="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-delete"
                    @click="delDiglog(scope.row.attr_id)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-edit"
                    @click="showeditDialog(scope.row.attr_id)"
                  >
                    编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="配置管理" name="only">
            <el-button
              type="primary"
              size="mini"
              :disabled="isButtonDisabled"
              @click="dialogVisible = true"
              >添加属性</el-button
            >

            <el-table :data="onlyTableData" style="width: 100%" border>
              <el-table-column type="expand">
                <template v-slot="scope">
                  <el-tag
                    closable
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    @close="handleClose(index, scope.row)"
                  >
                    {{ item }}
                  </el-tag>
                  <el-input
                    style="width: 100px"
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="#" type="index"> </el-table-column>
              <el-table-column label="属性名称" prop="attr_name">
              </el-table-column>
              <el-table-column label="操作">
                <template v-slot="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="showeditDialog(scope.row.attr_id)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="delDiglog(scope.row.attr_id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
    <!-- 添加弹框 -->
    <el-dialog
      :title="'添加' + tittext"
      :visible.sync="dialogVisible"
      width="50%"
      @close="handleCloseFrom"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClose">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改弹框 -->
    <el-dialog
      :title="'修改' + tittext"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="edithandleCloseFrom"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editparams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [], // 存储分类列表数据

      selectedCateKeys: [], //用户在级联下拉菜单中选中的分类id
      dialogVisible: false,
      editdialogVisible: false, //控制修改弹框
      cateProps: {
        //配置级联菜单中数据如何展示
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      activeName: "many",
      //用来保存动态参数数据
      manyTableData: [],
      //用来保存静态属性数据
      onlyTableData: [],
      addForm: {
        attr_name: "",
      },
      // 修改表单
      editForm: {},
      //表单验证
      rules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
    };
  },
  // Vue实例创建完成以后执行 数据可用
  created() {
    this.getCateList();
  },
   
  methods: {
    async getCateList() {
      let res = await this.$axios.get(
        "https://www.liulongbin.top:8888/api/private/v1/categories"
      );
      console.log(res);
      let { meta, data } = res;
      if (meta.status == 200) {
        this.cateList = data;
      }
    },
    handleChange() {
      this.getParamsData();
    },
    // tab 页签处理事件
    handleTabClick() {
      // console.log(this.activeName)
      this.getParamsData();
    },
    // 获取参数的数据
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      console.log(this.selectedCateKeys);
      // 获取对应的参数

      let res = await this.$axios.get(
        `https://www.liulongbin.top:8888/api/private/v1/categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );

      let { meta, data } = res;

      if (meta.status == 200) {
        console.log(meta, data);
        data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
          item.inputVisible = false;
          item.inputValue = "";
        });
      }
      if (this.activeName === "many") {
        this.manyTableData = data;
      } else {
        this.onlyTableData = data;
      }
    },
    handleCloseFrom() {
      this.$refs.addForm.resetFields();
    },
    // 修改清空表单
    edithandleCloseFrom() {
      this.$refs.editForm.resetFields();
    },
    addClose() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          // alert('submit!');
          let res = await this.$axios.post(
            `https://www.liulongbin.top:8888/api/private/v1/categories/${this.cateId}/attributes`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          console.log(res);
          let { meta } = res;
          if (meta.status == 201) {
            this.$message.success(meta.msg);

            this.getParamsData();
            this.dialogVisible = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 修改
    async showeditDialog(attr_id) {
      let res = await this.$axios.get(
        `https://www.liulongbin.top:8888/api/private/v1/categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      //  console.log(res);
      let { meta, data } = res 
    //   .data;
      if (meta.status == 200) {
        this.editForm = data;
      }
      this.editdialogVisible = true;
    },
    // 修改
    editparams() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          // alert('submit!');
          let res = await this.$axios.put(
            `https://www.liulongbin.top:8888/api/private/v1/categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          console.log(res);
          let { meta } = res;
          if (meta.status == 200) {
            this.$message.success(meta.msg);
            this.getParamsData();
            this.editdialogVisible = false;
          } else {
            this.$message.error(meta.msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除
    async delDiglog(id) {
      let res = await this.$axios.delete(
        `https://www.liulongbin.top:8888/api/private/v1/categories/${this.cateId}/attributes/${id}`
      );//.data
      console.log(res);
      let { meta } = res;
      if (meta.status == 200) {
        this.$message.success(meta.msg);
        this.getParamsData();
      } else {
        this.$message.error(meta.msg);
      }
    },
    handleInputConfirm(row) {
      console.log("ik");

      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
    showInput(item) {
      item.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleClose(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    },
    saveAttrVals(row) {
      this.$axios
        .put(
          `https://www.liulongbin.top:8888/api/private/v1/categories/${this.cateId}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(" "),
          }
        )
        .then((res) => {
          console.log(res);
          if (res.data.meta.status == 200) {
            this.$message.success(res.data.meta.msg);
          }
        });
    },
  },
  // 过滤器
  filter: {},
  // 计算属性
  computed: {
    isButtonDisabled() {
      if (this.selectedCateKeys.length == 3) {
        return false;
      } else {
        return true;
      }
    },
    // 选择器第三项id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      } else {
        return null;
      }
    },
    // 弹框标题
    tittext() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style scoped>
.el-tag {
  margin: 0 20px;
}
</style>
